# coding=utf-8
import json

import requests


class BaiDuTrans(object):

    def __init__(self, query_string):
        self.url = "http://fanyi.baidu.com/basetrans"
        self.query_string = query_string
        self.headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"}
        self.langdetect_url = "http://fanyi.baidu.com/langdetect"

    def get_post_data(self):
        data = {"query": self.query_string}
        # 发送请求，获取响应
        json_str = self.parse_url(self.langdetect_url, data)
        # 提取数据
        lan = json.loads(json_str)
        to = "en" if lan == "zh" else "zh"
        post_data = {"query": self.query_string,
                     "from": lan,
                     "to": to}
        return post_data

    def parse_url(self, url, data):
        response = requests.post(url, data=data, headers=self.headers)
        # print(response.status_code)
        return response.content.decode()

    def get_result(self, json_data):
        data_dict = json.loads(json_data)
        res_data = data_dict["trans"][0]["dst"]
        print("{}:{}".format(self.query_string, res_data))

    def run(self):
        # url, post_data
        post_data = self.get_post_data()

        # 发送请求，获取响应
        json_data = self.parse_url(self.url, post_data)

        # 提取数据
        # data_dict = json.loads(json_data)
        # res_data = data_dict["trans"][0]["dst"]
        # print("{}:{}".format(self.query_string, res_data))
        self.get_result(json_data)


if __name__ == '__main__':
    q = input("词条：")
    bt = BaiDuTrans(q)
    bt.run()
